package com.irdstudio.efp.flow.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.*;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.efp.flow.common.constance.FlowConstance;
import com.irdstudio.efp.flow.executor.util.AbstractController;
import com.irdstudio.efp.flow.service.FlowCommonService;
import com.irdstudio.efp.flow.service.FlowRepulseUtil;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.riskm.service.facade.LmtFreezeAppService;
import com.irdstudio.efp.riskm.service.facade.LmtTerminateAppService;
import com.irdstudio.efp.riskm.service.vo.LmtFreezeAppVO;
import com.irdstudio.efp.riskm.service.vo.LmtTerminateAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/api")
public class LmtTerminateAppController extends AbstractController {

	@Autowired
	@Qualifier("dbSeqService")
	private SequenceService sequenceService;

	@Autowired
	@Qualifier("accLoanService")
	private AccLoanService accLoanService;

	@Autowired
	@Qualifier("bizFlowInfoService")
	private BizFlowInfoService bizFlowInfoService;

	@Autowired
	@Qualifier("pubSysInfoService")
	private PubSysInfoService pubSysInfoService;

	@Autowired
	@Qualifier("flowUrlConfigService")
	private FlowUrlConfigService flowUrlConfigService;

	@Autowired
	@Qualifier("lmtTerminateAppService")
	private LmtTerminateAppService lmtTerminateAppService;

	@Autowired
	@Qualifier("lmtFreezeAppService")
	private LmtFreezeAppService lmtFreezeAppService;

	@Autowired
	private FlowCommonService flowCommonService;

	@Autowired
	@Qualifier("flowRepulseUtil")
	private FlowRepulseUtil flowRepulseUtil;

	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;
	/**
	 * 列表数据查询
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/lmt/terminate/apps", method = RequestMethod.POST)
	public @ResponseBody
	ResponseData<List<LmtTerminateAppVO>> queryLmtTerminateAppAll(@RequestBody LmtTerminateAppVO vo) {
		List<LmtTerminateAppVO> outputVo = null;
		Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		switch (dataRuleType) {
			case Owner:
				outputVo = lmtTerminateAppService.queryAllOwner(vo);
				break;
			case CurrOrg:
				outputVo = lmtTerminateAppService.queryAllCurrOrg(vo);
				break;
			case CurrDownOrg:
				outputVo = lmtTerminateAppService.queryAllCurrDownOrg(vo);
				break;
			case CurrOwnerPrd:
				outputVo = lmtTerminateAppService.queryAllCurrOwnerPrd(vo);
				break;
			default:
				outputVo = lmtTerminateAppService.queryAllCurrOrg(vo);
				break;
		}
		flowCommonService.displayOrgName(outputVo, "orgCode", "orgName");
		flowCommonService.displayUserName(outputVo, "cusManager", "cusManagerName");
		flowCommonService.displayUserName(outputVo, "createUser", "createUserName");
		flowCommonService.displayUserName(outputVo, "lastUpdateUser", "lastUpdateUserName");
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 * @return outputVo
	 */
	@RequestMapping(value="/lmt/terminate/app", method=RequestMethod.GET)
	public @ResponseBody ResponseData<LmtTerminateAppVO> queryByPk(LmtTerminateAppVO inVo) {
		LmtTerminateAppVO outputVo = lmtTerminateAppService.queryByPk(inVo);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键删除信息
	 * @param inLmtTerminateAppVo
	 * @return
	 */
	@RequestMapping(value="/lmt/terminate/app", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody LmtTerminateAppVO inLmtTerminateAppVo) {
		int outputVo = lmtTerminateAppService.deleteByPk(inLmtTerminateAppVo);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键更新信息
	 * @param inLmtTerminateAppVo
	 * @return
	 */
	@RequestMapping(value="/lmt/terminate/app", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody LmtTerminateAppVO inLmtTerminateAppVo) {
		int outputVo = 0;
		// 申请时间= 当前时间
		inLmtTerminateAppVo.setApplyDate(TimeUtil.getCurrentDate());
		// 最后更新时间= 当前时间
		inLmtTerminateAppVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		inLmtTerminateAppVo.setAprvComment("");
		inLmtTerminateAppVo.setAprvDate("");
		inLmtTerminateAppVo.setAprvUserCode("");
		outputVo = lmtTerminateAppService.updateByPk(inLmtTerminateAppVo);
		return getResponseData(outputVo);
	}

	/**
	 * 新增数据
	 * @param inLmtTerminateAppVo
	 * @return
	 */
	@RequestMapping(value="/lmt/terminate/app", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertLmtTerminateApp(@RequestBody LmtTerminateAppVO inLmtTerminateAppVo) {
		int outputVo = 0;
		LmtFreezeAppVO lmtFreezeAppVO = new LmtFreezeAppVO();
		lmtFreezeAppVO.setLmtContNo(inLmtTerminateAppVo.getLmtContNo());
		// 判断是否有“审批中”的额度冻结申请
		List<LmtFreezeAppVO> qsoutputVo1 = lmtFreezeAppService.queryLmtContNoByPk(lmtFreezeAppVO);
		if (qsoutputVo1.size() > 0){
			outputVo = -1;
			return setResponseMessage(outputVo, "该授信额度信息，存在未处理完成的额度冻结操作！ ");
		}
		// 判断是否有“审批中”的额度终止申请
		List<LmtTerminateAppVO> qsoutputVo = lmtTerminateAppService.querylmtTerminateByPk(inLmtTerminateAppVo);
		if (qsoutputVo.size()>0){
			outputVo = -1;
			return setResponseMessage(outputVo, "该授信额度信息，存在未处理完成的额度终止操作！ ");
		}
		setUserInfoToVO(inLmtTerminateAppVo);
		// 归属机构= 当前登陆人所在机构号
		inLmtTerminateAppVo.setOrgCode(inLmtTerminateAppVo.getLoginUserOrgCode());
		// 最后修改人= 当前登陆用户编号
		inLmtTerminateAppVo.setLastUpdateUser(inLmtTerminateAppVo.getLoginUserId());
		// 创建时间= 当前时间
		inLmtTerminateAppVo.setCreateTime(TimeUtil.getCurrentDateTime());
		// 申请时间= 当前时间
		inLmtTerminateAppVo.setApplyDate(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
		// 最后更新时间= 当前时间
		inLmtTerminateAppVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		// 审批状态 = 待发起
		inLmtTerminateAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
		try {
			//  终止流水号
			String tSeq = sequenceService.getSequence("T_SERNO","null","null");
			inLmtTerminateAppVo.setTerminateSerno(tSeq);
			outputVo = lmtTerminateAppService.insertLmtTerminateApp(inLmtTerminateAppVo);

		} catch (Exception e) {
			logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
			outputVo = -1;
		}
		return getResponseData(outputVo);

	}

	/**
	 * 问题编号：<br/>
	 * 功能描述：根据证件类型和证件号码查询借据表<br/>
	 * 创建时间：2019年8月19日<br/>
	 */
	@RequestMapping(value="/lmt/terminate/app/acc/loans", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<AccLoanVO>> queryAccLoanAll(@RequestBody LmtTerminateAppVO lmtTerminateAppVO) {
		List<AccLoanVO> outputVo = null;
		AccLoanVO accLoanVO = new AccLoanVO();
		String certType = lmtTerminateAppVO.getCertType();
		String certCode = lmtTerminateAppVO.getCertCode();
		String prdCode = lmtTerminateAppVO.getPrdCode();
		accLoanVO.setCertCode(certCode);
		accLoanVO.setCertType(certType);
		accLoanVO.setPrdCode(prdCode);
		accLoanVO.setPage(lmtTerminateAppVO.getPage());
		accLoanVO.setSize(lmtTerminateAppVO.getSize());
		accLoanVO.setTotal(lmtTerminateAppVO.getTotal());
		outputVo = accLoanService.queryAccLoan(accLoanVO);
		return getResponseData(outputVo);
	}

	/**
	 * 问题编号：<br/>
	 * 功能描述：提交数据<br/>
	 * 创建时间：2019年8月20日<br/>
	 * @param inLmtTerminateAppVo
	 * @return
	 */
	@RequestMapping(value="/lmt/terminate/app/submit", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> submit(@RequestBody LmtTerminateAppVO inLmtTerminateAppVo) {
		int outputVo = 0;
		setUserInfoToVO(inLmtTerminateAppVo);
		ResponseData<Integer> integerResponseData =null;
		if(StringUtil.isNullorBank(inLmtTerminateAppVo.getTerminateSerno())){
			//  新增数据
			integerResponseData = insertLmtTerminateApp(inLmtTerminateAppVo);
			if(!integerResponseData.getCode().equals("0")) {
				outputVo = -1;
				return setResponseMessage(outputVo, "该授信额度信息，存在未处理完成的额度冻结操作！");
			}
		}else{
			//  修改数据
			integerResponseData = updateByPk(inLmtTerminateAppVo);
			if(!integerResponseData.getCode().equals("0")) {
				outputVo = -1;
				return setResponseMessage(outputVo, "该授信额度信息，存在未处理完成的额度终止操作！");
			}
		}

		if(inLmtTerminateAppVo.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_05)){
			flowRepulseUtil.cleanRepulseAllInfo(inLmtTerminateAppVo.getTerminateSerno());
		}
		// 发起流程
		logger.info("即将发起额度限额审批流程，信息为:" + JSON.toJSONString(inLmtTerminateAppVo));
		// 事件ID
		String eventId = "mLmtTerminateAppEnter";
		String flowId = "FW20190910000000004";
		inLmtTerminateAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_02);

		BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
		bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_07);
		bizFlowInfoVO.setBizFlowId(flowId);
		List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);

		// 获取流程ID
		logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
		if (Objects.nonNull(listFlow) && listFlow.size()>0) {
			bizFlowInfoVO = listFlow.get(0);
			flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
		} else {
			//提交失败 待发起
			inLmtTerminateAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
			outputVo = -1;
			return setResponseMessage(outputVo, "未配置相关信息提交失败!");
		}
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		// 业务法人机构
		eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
		// 业务流水号
		eVo.setE_bizSerno(inLmtTerminateAppVo.getTerminateSerno());
		eVo.setFlowId(flowId);
		//事件ID
		eVo.setEventId(eventId);
		eVo.setData(inLmtTerminateAppVo);
		eVo.setG_bizSerno(inLmtTerminateAppVo.getTerminateSerno());
		if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
			outputVo = -1;
			return setResponseMessage(outputVo, "发起审批流程失败!原因: 流程岗位已失效");
		}
		try {
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			//更新 申请日期
			inLmtTerminateAppVo.setApplyDate(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
			outputVo = lmtTerminateAppService.updateByPk(inLmtTerminateAppVo);
		} catch (Exception e) {
			// 发起失败
			e.printStackTrace();
			logger.error("RscAdjustAppVO", e.getMessage());
			outputVo = -1;
			return setResponseMessage(outputVo, "发起额度终止申请审批流程失败!原因: " + e.getMessage());
		}
		return getResponseData(outputVo);
	}

	private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
		ResponseData<Integer> responseData = new ResponseData<Integer>();
		responseData.setMessage(message);
		responseData.setCode(ApplicationConstance.FAILURE);
		responseData.setSuccess(true);
		return responseData;
	}
}
